package com.winapi.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.winapi.project.common.BaseResponse;
import com.winapi.project.common.DeleteRequest;
import com.winapi.project.common.ErrorCode;
import com.winapi.project.common.ResultUtils;
import com.winapi.project.exception.BusinessException;
import com.winapi.project.model.dto.user.*;
import com.winapi.project.model.vo.UserDevKeyVO;
import com.winapi.project.model.vo.UserVO;
import com.winapi.project.service.UserService;
import com.winapi.project.utils.FileUploadUtil;
import com.winapi.winapicommon.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
private static final String userLog="用户模块-";
    @Resource
    private UserService userService;

    // region 登录相关

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        log.info(userLog+"注册-进入注册后端接口.......");
        if (userRegisterRequest == null) {
            log.error(userLog+"注册-请求参数为空");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            log.error(userLog+"注册-账号，密码，确认密码有为空的情况");
            return null;
        }
        log.info(userLog+"注册-开始调用用户业务逻辑层的注册方法");
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        log.info(userLog+"注册-结束调用用户业务逻辑层的注册方法");
        log.info(userLog+"注册-注册后端接口调用结束.......");
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request, HttpServletResponse response) {
        log.info(userLog+"登录-进入登录后端接口.......");
        if (userLoginRequest == null) {
            log.error(userLog+"登录-请求参数为空");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            log.error(userLog+"登录-用户名或密码为空");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info(userLog+"登录-进入登录业务层");
        User user = userService.userLogin(userAccount, userPassword, request,response);
        log.info(userLog+"登录-结束登录业务层");
        log.info(userLog+"登录-登录后端接口调用结束.......");
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        log.info(userLog+"登出-进入登出接口.....");
        if (request == null) {
            log.error(userLog+"登录-请求为空");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info(userLog+"登录-进入登录业务层");
        boolean result = userService.userLogout(request);
        log.info(userLog+"登录-结束登录业务层");
        log.info(userLog+"登录-结束登录接口.....");
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<UserVO> getLoginUser(HttpServletRequest request) {
        log.info(userLog+"获取登录态-进入接口.....");
        User user = userService.getLoginUser(request);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        log.info(userLog+"获取登录态-结束接口.....");
        return ResultUtils.success(userVO);
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        log.info(userLog+"添加用户-进入接口.....");
        if (userAddRequest == null) {
            log.error(userLog+"添加用户-请求参数为空");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        boolean result = userService.save(user);
        log.info(userLog+"添加用户-将这个用户插入用户表");
        if (!result) {
            log.error(userLog+"添加用户-添加用户失败");
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        log.info(userLog+"添加用户-结束接口.....");
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        log.info(userLog+"删除用户-进入接口.....");
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            log.error(userLog+"删除用户-参数为空/用户id不合法");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info(userLog+"删除用户-进入根据id删除用户业务层.....");
        boolean b = userService.removeById(deleteRequest.getId());
        log.info(userLog+"删除用户-结束根据id删除用户业务层.....");
        log.info(userLog+"删除用户-结束接口.....");
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        log.info(userLog+"更新用户-进入接口....");
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            log.error(userLog+"更新用户-参数为空/用户id不合法");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        log.info(userLog+"更新用户-进入更新用户业务层....");
        boolean result = userService.updateById(user);
        log.info(userLog+"更新用户-结束更新用户业务层....");
        log.info(userLog+"更新用户-结束接口....");
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取用户
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<UserVO> getUserById(int id, HttpServletRequest request) {
        log.info(userLog+"根据id获取用户-进入接口....");
        if (id <= 0) {
            log.error(userLog+"根据id获取用户-用户id不合法");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        log.info(userLog+"根据id获取用户-结束接口....");
        return ResultUtils.success(userVO);
    }

    /**
     * 获取用户列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<UserVO>> listUser(@RequestBody UserQueryRequest userQueryRequest, HttpServletRequest request) {
        log.info(userLog+"获取用户列表-进入接口....");
        User userQuery = new User();
        log.info(userLog+"获取用户列表-创建一个用户");
        if (userQueryRequest != null) {
            BeanUtils.copyProperties(userQueryRequest, userQuery);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
        List<User> userList = userService.list(queryWrapper);
        log.info(userLog+"获取用户列表-根据请求参数查询相关用户");
        List<UserVO> userVOList = userList.stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());
        log.info(userLog+"获取用户列表-进入接口....");
        return ResultUtils.success(userVOList);
    }

    /**
     * 分页获取用户列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<UserVO>> listUserByPage(UserQueryRequest userQueryRequest, HttpServletRequest request) {
        log.info(userLog+"分页获取用户列表-进入接口....");
        long current = 1;
        long size = 10;
        User userQuery = new User();
        if (userQueryRequest != null) {
            BeanUtils.copyProperties(userQueryRequest, userQuery);
            current = userQueryRequest.getCurrent();
            size = userQueryRequest.getPageSize();
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
        log.info(userLog+"分页获取用户列表-进入分页查询业务层....");
        Page<User> userPage = userService.page(new Page<>(current, size), queryWrapper);
        log.info(userLog+"分页获取用户列表-结束分页查询业务层....");
        Page<UserVO> userVOPage = new PageDTO<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
        List<UserVO> userVOList = userPage.getRecords().stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());
        userVOPage.setRecords(userVOList);
        log.info(userLog+"分页获取用户列表-结束接口....");
        return ResultUtils.success(userVOPage);
    }

    /**
     * 更新头像
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/update/avatar")
    public BaseResponse<Boolean> updateUserAvatar(@RequestParam(required = false) MultipartFile file,HttpServletRequest request){
        log.info(userLog+"更新头像-进入更新头像接口....");
        if (!FileUploadUtil.validate(file)) {
            log.error(userLog+"更新头像-上传文件不存在或者格式不是图片");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.updateUserAvatar(file,request);
        log.info(userLog+"更新头像-结束更新头像接口....");
//        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE,user1);
        return ResultUtils.success(result);
    }

    /**
     * 获取密钥
     * @param request
     * @return
     */
    @GetMapping("/key")
    public BaseResponse<UserDevKeyVO> getKey(HttpServletRequest request){
        log.info(userLog+"获取密钥-进入获取密钥接口....");
        UserDevKeyVO userDevKeyVO=userService.getKey(request);
        log.info(userLog+"获取密钥-结束获取密钥接口....");
        return ResultUtils.success(userDevKeyVO);
    }

    /**
     * 重新生成密钥
     * @param request
     * @return
     */
    @PostMapping("/gen/key")
    public BaseResponse<UserDevKeyVO> genKey(HttpServletRequest request) {
        log.info(userLog+"重新生成密钥-进入接口....");
        UserDevKeyVO userDevKeyVO = userService.genkey(request);
        log.info(userLog+"重新生成密钥-结束接口....");
        return ResultUtils.success(userDevKeyVO);
    }
    // endregion
}
